package com.probox.common.entity.service.centre.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.*;
import java.util.stream.Collectors;

import com.probox.common.core.utils.StringUtils;
import com.probox.common.entity.domain.centre.CustomerInfo;
import com.probox.common.entity.mapper.centre.CentreCustomerInfoMapper;
import com.probox.common.entity.mapper.centre.CentreOrderInfoMapper;
import com.probox.common.entity.mapper.centre.CentreProductCountMapper;
import com.probox.common.entity.service.centre.ICustomerInfoService;
import com.probox.common.entity.vo.centre.customer.CustomerQueryVo;
import com.probox.common.entity.vo.centre.customer.MemberlVo;
import com.probox.common.entity.vo.centre.map.Legend;
import com.probox.common.entity.vo.centre.map.ProductAxisMap;
import com.probox.common.entity.vo.centre.map.Series;
import com.probox.common.entity.vo.centre.map.XAxis;
import com.probox.common.entity.vo.centre.order.OrderQueryVo;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.enums.ProductOptType;
import com.probox.common.core.enums.centreMemberDataEnum;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.order.api.domain.OrderQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

/**
 * 客户信息Service业务层处理
 *
 * @author zsy
 * @date 2021-07-23
 */

@Service
@Transactional
public class CentreCustomerInfoServiceImpl extends ServiceImpl<CentreCustomerInfoMapper, CustomerInfo> implements ICustomerInfoService {
    @Autowired
    private CentreCustomerInfoMapper centreCustomerInfoMapper;

    @Autowired
    private CentreProductCountMapper centreProductCountMapper;

    @Autowired
    private CentreOrderInfoMapper centreOrderInfoMapper;

    /**
     * 成交总数
     * @return
     */
    @Override
    public Integer selectCustomerTotal(OrderQuery query){
        QueryWrapper<CustomerInfo> customerInfoQueryWrapper = new QueryWrapper<>();
        //customerInfoQueryWrapper.eq("PLATFORM_UID",SecurityUtils.getPlatformId());
        customerInfoQueryWrapper.eq("STATUS", DataStatus.valid.getKey());
        if (StringUtils.isNotEmpty(query.getStartDate())){
            customerInfoQueryWrapper.ge("CREATE_TIME", query.getStartDate());
            customerInfoQueryWrapper.le("CREATE_TIME", query.getEndDate());
        }
        return centreCustomerInfoMapper.selectCount(customerInfoQueryWrapper);
    }

    @Override
    public Integer selectStoreCustomerTotal(OrderQueryVo queryVo) {
        return centreCustomerInfoMapper.selectStoreCustomerTotal(queryVo);
    }

    /**
     * 查询新增客户
     * @return
     */
    @Override
    public Integer selectNewlyCustomer(CustomerQueryVo customerQueryVo){
        QueryWrapper<CustomerInfo> customerInfoQueryWrapper = new QueryWrapper<>();
        customerInfoQueryWrapper.eq("PLATFORM_UID",SecurityUtils.getPlatformId());
        customerInfoQueryWrapper.eq("STATUS", DataStatus.valid.getKey());
        Date StartTime = null;
        Date EndTime = null;
        if (customerQueryVo.getStartTime()!=null){
            StartTime = DateUtil.beginOfDay(customerQueryVo.getStartTime());
        }
        if (customerQueryVo.getEndTime()!=null){
            EndTime = DateUtil.endOfDay(customerQueryVo.getEndTime());
        }
        customerInfoQueryWrapper.ge("CREATE_TIME", StartTime);
        customerInfoQueryWrapper.le("CREATE_TIME", EndTime);
        return centreCustomerInfoMapper.selectCount(customerInfoQueryWrapper);
    }

    /**
     * 查询新增客户
     * @return
     */
    @Override
    public ProductAxisMap selectNewlyCustomerMap(CustomerQueryVo customerQueryVo){
        List<HashMap> hashMaps = centreCustomerInfoMapper.selectNewlyCustomerMap(customerQueryVo);
        ProductAxisMap productAxisMap = new ProductAxisMap();
        productAxisMap.setTitle("近七天新用户统计图");

        List orderDate = getDate(customerQueryVo.getStartTime(), customerQueryVo.getEndTime());
        XAxis xAxis = new XAxis();
        xAxis.setData(orderDate);

        Series series = new Series();
        series.setColor("#0072E3");
        series.setData(seriesData(hashMaps, orderDate));

        ArrayList<Series> seriesList = new ArrayList<>();
        seriesList.add(series);

        productAxisMap.setXAxis(xAxis);
        productAxisMap.setSeries(seriesList);


        return productAxisMap;
    }

    /**
     * 查询会员数据
     * @param customerQueryVo
     * @return
     */
    @Override
    public MemberlVo getMemberData(CustomerQueryVo customerQueryVo) {
        MemberlVo memberlVo = new MemberlVo();
        memberlVo.setMembershipNewlyNumber( centreCustomerInfoMapper.selectMemberNewly(customerQueryVo));
        memberlVo.setMembershipTotalNumber(centreCustomerInfoMapper.selectMembershipTotal(customerQueryVo));
        memberlVo.setMemberStoredNumber(centreCustomerInfoMapper.selectMemberStored(customerQueryVo));
        memberlVo.setMemberUpgradeNumber(centreCustomerInfoMapper.selectMemberUpgrade(customerQueryVo));
        return memberlVo;
    }

    /**
     * 查询会员访问数量
     * @param customerQueryVo
     * @return
     */
    @Override
    public Integer selectMemberVisitorsData(CustomerQueryVo customerQueryVo) {

        return  centreProductCountMapper.selectMemberVisitorsData(customerQueryVo);
    }

    /**
     * 查询加购会员数量
     * @param customerQueryVo
     * @return
     */
    @Override
    public Integer selectMemberAddCarData(CustomerQueryVo customerQueryVo) {
        return  centreProductCountMapper.selectMemberData(customerQueryVo,ProductOptType.addCar.getKey());
    }

    /**
     * 查询成交会员数量
     * @param customerQueryVo
     * @return
     */
    @Override
    public Integer selectMakeMemberTotal(CustomerQueryVo customerQueryVo) {
        return  centreOrderInfoMapper.selectMakeMemberTotal(customerQueryVo);
    }

    /**
     * 查询会员活跃数据
     * @param customerQueryVo
     * @return
     */
    @Override
    public MemberlVo getMemberBehaviorData(CustomerQueryVo customerQueryVo) {
        MemberlVo memberlVo = new MemberlVo();
        memberlVo.setMemberMakeNumber( centreCustomerInfoMapper.selectMemberNewly(customerQueryVo));
        memberlVo.setMemberShoppingNumber(centreCustomerInfoMapper.selectMembershipTotal(customerQueryVo));
        memberlVo.setMemberStoredNumber(centreCustomerInfoMapper.selectMemberStored(customerQueryVo));
        memberlVo.setMembershipVisitNumber(centreCustomerInfoMapper.selectMemberUpgrade(customerQueryVo));
        return memberlVo;
    }

    /**
     * 查询订单总额数据汇总
     * @param customerQueryVo
     * @return
     */
    @Override
    public ProductAxisMap getMemberTotalMap(CustomerQueryVo customerQueryVo) {
        Date endTime = new Date();
        Date startTime = DateUtil.lastMonth();
        customerQueryVo.setStartTime(startTime);
        customerQueryVo.setEndTime(startTime);

        //生成近三十天日期
        List<String> date = getOrderDate(DateUtil.offsetDay(endTime, -1),startTime );

        //新增会员Map
        List<HashMap> memberMap = centreCustomerInfoMapper.selectMemberNewlyMap(customerQueryVo);
        //升级会员map
        List<HashMap> memberUpgradeMa = centreCustomerInfoMapper.selectMemberUpgradeMap(customerQueryVo);


        XAxis xAxis = new XAxis();
        xAxis.setData(date);

        List seriesList = new ArrayList();
        List list = seriesData(memberMap, date);
        Series series = buildSeriesMap(list, centreMemberDataEnum.memberNewly.getKey());
        seriesList.add(series);

        list = seriesData(memberUpgradeMa, date);
        series = buildSeriesMap(list, centreMemberDataEnum.memberUpgrade.getKey());
        seriesList.add(series);

        Legend legend = buildLegendMap(seriesList);
        return buildProductAxisMap(seriesList,xAxis,legend);
    }

    /**
     * 查询收藏商品会员数量
     * @param customerQueryVo
     * @return
     */
    @Override
    public Integer selectMembershipCollectNumber(CustomerQueryVo customerQueryVo) {
        return centreProductCountMapper.selectMemberData(customerQueryVo, ProductOptType.collect.getKey() );
    }

    /**
     * 查询当前平台会员id
     * @param customerQueryVo
     * @return
     */
    @Override
    public List selectMemberIdList(CustomerQueryVo customerQueryVo){
        return centreCustomerInfoMapper.selectMemberIdList(customerQueryVo);
    }

    /**
     * 成交客户数
     * @return
     */
    @Override
    public Integer selectMakeClientTotal(CustomerQueryVo customerQueryVo){
        OrderQueryVo orderQueryVo = new OrderQueryVo();
        if (customerQueryVo.getStartTime()!=null){
            orderQueryVo.setStartTime(DateUtil.beginOfDay(customerQueryVo.getStartTime()));
        }
        if (customerQueryVo.getEndTime()!=null){
            orderQueryVo.setEndTime(DateUtil.endOfDay(customerQueryVo.getEndTime()));
        }

        return centreOrderInfoMapper.selectMakeClientTotal(orderQueryVo);
    }

    /**
     * 访客数
     * @return
     */
    @Override
    public Integer selectVisitorsTotal(CustomerQueryVo customerQueryVo){
        String begTime = null;
        String endTime = null;
        if (customerQueryVo.getStartTime()!=null){
             begTime =  DateUtil.formatDate(DateUtil.beginOfDay(customerQueryVo.getStartTime()));
        }
        if (customerQueryVo.getEndTime()!=null){
             endTime = DateUtil.formatDate(DateUtil.endOfDay(customerQueryVo.getEndTime()));
        }
        return centreProductCountMapper.selectProductVisitorsData(SecurityUtils.getPlatformId(), begTime,endTime);
    }


    /**
     * 获取某段时间内的日期集合
     * @param startTime
     * @param endTime
     * @return
     */
    public static List getDate(Date startTime, Date endTime){
        List list = new ArrayList<>();
        long betweenDay = DateUtil.between(startTime, endTime, DateUnit.DAY);
        for (int i = 0; i <betweenDay ; i++) {
            startTime = DateUtil.offsetDay(startTime, 1);
            String format = DateUtil.format(startTime, "yyyy-MM-dd");
            list.add(format);
        }
        return list;
    }

    /**
     * 构建 seriesData 下的数据
     * @param list
     * @param date
     * @return
     */
    public List<Integer> seriesData(List<HashMap> list , List<String> date){

        List<Integer> collect = date.stream().map(o -> {
            Integer total = 0;
            HashMap hashMap = new HashMap();
            hashMap = list.stream().filter(i -> i.get("date").equals(o)).findAny().orElse(null);
            if (hashMap!=null){
                try {
                    total = Integer.parseInt(hashMap.get("total").toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return total;
        }).collect(Collectors.toList());
        return collect;
    }
    /**
     * 获取某段时间内的日期集合
     * @param startTime
     * @param endTime
     * @return
     */
    public static List getOrderDate(Date startTime, Date endTime){
        List list = new ArrayList<>();
        long betweenDay = DateUtil.between(startTime, endTime, DateUnit.DAY);
        for (int i = 0; i <betweenDay ; i++) {
            endTime = DateUtil.offsetDay(endTime, 1);
            String format = DateUtil.format(endTime, "yyyy-MM-dd");
            list.add(format);
        }
        return list;
    }

    /**
     * 构建buildSeries对象
     * @param collect
     * @param type
     * @return
     */
    public Series buildSeriesMap(List<Double> collect, String type){
        Series series = new Series();
        series.setData(collect);
        series.setType("line");
        series.setStack("总量");
        if (centreMemberDataEnum.memberNewly.getKey().equals(type)){
            series.setName(centreMemberDataEnum.memberNewly.getValue());
            series.setColor("#00DB00");
        }else if (centreMemberDataEnum.memberUpgrade.getKey().equals(type)){
            series.setName(centreMemberDataEnum.memberUpgrade.getValue());
            series.setColor("#930000");
        }else if (centreMemberDataEnum.memberStored.getKey().equals(type)){
            series.setName(centreMemberDataEnum.memberStored.getValue());
            series.setColor("#F7BE81");
        }
        return series;
    }
    /**
     * 构建buildLegendMap对象
     * @return
     */
    public Legend buildLegendMap(List<Series> list){
        Legend legend = new Legend();
        List datalist = new ArrayList<>();
        for (Series i : list){
            datalist.add(i.getName());
        }
        legend.setData(datalist);
        return legend;
    }

    /**
     * 构建 ProductAxisMap 对象
     * @return
     */
    public ProductAxisMap  buildProductAxisMap( List<Series> seriesList , XAxis xAxis, Legend legend){
        ProductAxisMap productAxisMap = new ProductAxisMap();
        productAxisMap.setXAxis(xAxis);
        productAxisMap.setSeries(seriesList);
        productAxisMap.setLegend(legend);
        return productAxisMap;
    }

}
